package com.lwq.code;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 * Author: LiuWenQing
 * Datetime: 2021/6/15
 */
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {


    /**
     *  读空闲时间(秒)
     */
    public final Duration writeIdle = Duration.ofSeconds(15);

    /**
     *  写接空闲时间(秒)
     */
    public final Duration readIdle = Duration.ofSeconds(20);

    private final ChannelHandler loggingHandler = new LoggingHandler();

    @Override
    protected void initChannel(SocketChannel sc) {
        ChannelPipeline pipeline = sc.pipeline();
        //Http消息编码解码
        pipeline.addLast("http-codec", new HttpServerCodec());
        //Http消息组装
        pipeline.addLast("aggregator", new HttpObjectAggregator(Integer.MAX_VALUE));
        //WebSocket通信支持
        pipeline.addLast("http-chunked", new ChunkedWriteHandler());
        pipeline.addLast(new IdleStateHandler(readIdle.getSeconds(), writeIdle.getSeconds(), 0, TimeUnit.SECONDS));
        pipeline.addLast(loggingHandler);
        // 配置通道处理  来进行业务处理
        pipeline.addLast(new com.lwq.code.EventChannelHandler());
    }
}
